<?php

/*
 * Edit by xinli
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace api\mall\controller;

use api\portal\service\PromoteService;
use cmf\controller\RestBaseController;

use app\portal\model\UserPromoteRelationModel;
use app\portal\model\UserRewardDetailModel;
use api\mall\model\MedalUserModel;

/**
 * @OA\Tag(
 *     name="mall-promote",
 *     description="推广管理"
 * )
 */
class PromoteController extends RestBaseController
{
    protected function initialize()
    {
        parent::initialize();
        if (empty($this->user)) {
            $this->error('login');
        }
        online_record($this->userId);
    }
    
    /**
     * 推广海报下载
     * @OA\Get(
     *     tags={"mall-promote"},
     *     path="/mall/promote/poster_image",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function poster_image()
    {
        $request = request();
        $urlPromote = $request->domain() . '/portal/Page/promote?parent_id=' . $this->userId;

        $promoteService = new PromoteService();
        $posterPath = $promoteService->checkQrCode($urlPromote, $this->user['user_nickname'], cmf_get_image_url($this->user['avatar']));

        header('Content-Type: image/png');
        readfile($posterPath);
        unlink($posterPath);
        die();
    }
    
    /**
     * 推广海报下载测试
     * @OA\Get(
     *     tags={"mall-promote"},
     *     path="/mall/promote/poster_image_base64",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function poster_image_base64()
    {
        $request = request();
        $urlPromote = $request->domain() . '/portal/Page/promote?parent_id=' . $this->userId;

        $promoteService = new PromoteService();
        $posterPath = $promoteService->checkQrCode($urlPromote, $this->user['user_nickname'], cmf_get_image_url($this->user['avatar']));

        // 将图片转换为Base64编码
        $imageData = base64_encode(file_get_contents($posterPath));
        $this->success('ok', $imageData);
        unlink($posterPath);
    }
    
    /**
     * 推广链接
     * @OA\Get(
     *     tags={"mall-promote"},
     *     path="/mall/promote/poster_link",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function poster_link()
    {
        $request = request();
        $urlPromote = $request->domain() . '/portal/Page/promote?parent_id=' . $this->user['id'];
        $this->success('ok', $urlPromote);
    }
    
    /**
     * @OA\Get(
     *     description="统计用户当前直邀下级及间推下级（只到第二级）的数量和通过邀请获得的星链石总数",
     *     tags={"mall-promote"},
     *     path="/mall/promote/inviteInfo",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function inviteInfo() {
        $userPromoteRelationModel = new UserPromoteRelationModel();
        $userRewardDetailModel = new UserRewardDetailModel();
        // 用户推广信息
        $userPromoteRelationData = $userPromoteRelationModel->where('user_id', $this->userId)->find();
        $userRewardCount = $userRewardDetailModel->where('user_id', $this->userId)->where('reward_type', '<>', 3)->sum('reward_count');

        // // 统计userId的全部直推用户的直推用户数
        // $userIndirectPromoteCount = $userPromoteRelationModel->where('parent_id', 'in', function($query){
        //     $query->name('user_promote_relation')->where('parent_id', $this->userId)->where('promote_status', 1)->field('user_id');
        // })->where('promote_status', 1)->count();

        // 勋章
        $medalUserModel = new MedalUserModel();
        $userPromoteMedal = $medalUserModel->alias('mum')
            ->leftJoin('cmf_medal m', 'mum.medal_id = m.id')
            ->where('mum.user_id', $this->userId)
            ->field('mum.medal_id, mum.status_i, mum.create_time, m.medal_name, m.medal_key, m.medal_url, m.medal_desc')->limit(1)->find();
        if ($userPromoteMedal) {
            foreach ($userPromoteMedal as &$item) {
                $item['medal_url'] = cmf_get_image_url($item['medal_url']);
            }
        }

        // 直推用户明细 联合查询用户表和推广关系表 包括下级用户邀请的人数总和 和下级用户给当前用户贡献的星链石总数
        $userPromoteDetail = $userPromoteRelationModel->alias('upr')
            ->join('cmf_user u', 'upr.user_id = u.id')
            ->where('upr.parent_id', $this->userId)
            ->where('upr.promote_status', 1)
            ->field('u.id, u.user_nickname, u.avatar, u.mobile, upr.create_time, upr.invite_size, upr.team_size')
            ->select();

        // 循环$userPromoteDetail，查询每个用户的下级用户数和贡献的星链石总数
        foreach ($userPromoteDetail as &$item) {
            // $item['directPromoteCount'] = $userPromoteRelationModel->where('parent_id', $item['id'])->where('promote_status', 1)->count();
            $item['reward_count'] = $userRewardDetailModel->where('user_id', $item['id'])->where('reward_type', 1)->sum('reward_count');
            $item['contribute_count'] = $userRewardDetailModel->where('user_id', $this->userId)->where('provide_user_id', $item['id'])->sum('reward_count');
            $item['avatar'] = cmf_get_image_url($item['avatar']);
            $item['mobile'] = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $item['mobile']);
        }

        $this->success('ok', [
            'invite_size' => $userPromoteRelationData['invite_size'],
            'team_size' => $userPromoteRelationData['team_size'],
            'reward_count' => $userRewardCount,
            'user_promote_medal' => $userPromoteMedal,
            'direct_promote_detail' => $userPromoteDetail
        ]);
    }

    /**
     * 测试
     * @OA\Get(
     *     tags={"mall-promote"},
     *     path="/mall/promote/test",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function test()
    {
        $promoteService = new PromoteService();
        $test = $promoteService->checkQrCode('http://wwww.baidu.com', 'test', 
            'http://metamall-1314752903.cos.ap-beijing.myqcloud.com/admin/20240121/9f5c25934a32da9010b6dcddd4c4144c.jpg#watermark');
        header('Content-Type: image/png');
        readfile($test);
        unlink($test);
    }

    /**
     * 测试2返回base64
     * @OA\Get(
     *     tags={"mall-promote"},
     *     path="/mall/promote/test2",
     *     @OA\Parameter(name="page",in="query",description="页码",required=false,@OA\Schema(type="integer")),
     *     @OA\Parameter(name="size",in="query",description="每页数量",required=false,@OA\Schema(type="integer")),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function test2()
    {
        $promoteService = new PromoteService();
        $test = $promoteService->checkQrCode('http://wwww.baidu.com', 'test', 
            'http://metamall-1314752903.cos.ap-beijing.myqcloud.com/admin/20240121/9f5c25934a32da9010b6dcddd4c4144c.jpg#watermark');
        // 将图片转换为Base64编码
        $imageData = base64_encode(file_get_contents($test));
        $this->success('ok', $imageData);
    }
}
